package com.yogee.topseller.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.trello.rxlifecycle.LifecycleTransformer;
import com.umeng.analytics.MobclickAgent;
import com.yogee.core.base.HttpView;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.loading.CustomProgressDialog;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.SharedPreferencesUtils;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.MainActivity;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.Demo;
import com.yogee.topseller.activity.FlashActivity;
import com.yogee.topseller.activity.MainActivity1;
import com.yogee.topseller.activity.PayActivity;
import com.yogee.topseller.activity.SearchActivity;
import com.yogee.topseller.activity.login.view.impl.RegisterLabelActivity;
import com.yogee.topseller.activity.login.view.impl.TermOfService;
import com.yogee.topseller.activity.my.ButlerServiceActivity;
import com.yogee.topseller.bean.BroadsideBean;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.bean.SearchKeyBean;
import com.yogee.topseller.fragment.home.FlashFragment;
import com.yogee.topseller.fragment.home.IntelligentScreeningFragment;
import com.yogee.topseller.fragment.home.PayCalendarFragment;
import com.yogee.topseller.fragment.home.RankingFragment;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.ImmersedStatusbarUtils;
import com.yogee.topseller.utils.LogUtils;
import com.yogee.topseller.utils.TabLayoutUtil;
import com.yogee.topseller.view.MyTabLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 首页
 * @auathor ${XiaoJianghong}
 * @date 2017/6/20.
 */

public class HomeFragment extends Fragment implements HttpView{

    @BindView(R.id.tl_product_type)
    MyTabLayout tlProductType;
//    @BindView(R.id.vp_product_list)
    public static ViewPager vpProductList;
    @BindView(R.id.home_search_tv)
    TextView homeSearchTv;
    @BindView(R.id.appbar_layout)
    AppBarLayout appbar_layout;
    @BindView(R.id.home_message_iv1)
    ImageView home_message_iv1;
    @BindView(R.id.home_message_iv)
    ImageView home_message_iv;
    @BindView(R.id.product_layout)
    CoordinatorLayout product_layout;

    Unbinder unbinder;
    //Fragment的数据集合
    List<Fragment> fragmentList = null;
    //标题数据集合
    List<String> titles = null;
    CustomProgressDialog pd;

    protected ImmersionBar mImmersionBar;
    private static final float PERCENTAGE_TO_HIDE_TITLE_DETAILS = 0.3f;
    private static final int ALPHA_ANIMATIONS_DURATION = 200;
    private boolean mIsTheTitleContainerVisible = true;
    /**
     * 是否在Fragment使用沉浸式
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(getActivity());
        mImmersionBar.init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null)
            mImmersionBar.destroy();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        vpProductList = (ViewPager) rootView.findViewById(R.id.vp_product_list);
        unbinder = ButterKnife.bind(this, rootView);
//        ImmersedStatusbarUtils.initAfterSetContentView(getActivity(),rootView.findViewById(R.id.appbar_layout));
//        if (isImmersionBarEnabled())
//            initImmersionBar();
//        mImmersionBar.transparentBar();
        LogUtils.e("homeinit","111111111111111111");
        fragmentList = new ArrayList<>();
        IntelligentScreeningFragment fragment = new IntelligentScreeningFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("isMj", 0);
        fragment.setArguments(bundle);

//        RankingFragment rankingFragment = new RankingFragment();

        IntelligentScreeningFragment fragment1 = new IntelligentScreeningFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putInt("isMj", 1);
        fragment1.setArguments(bundle1);

        IntelligentScreeningFragment fragment2 = new IntelligentScreeningFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putInt("isMj", 2);
        fragment2.setArguments(bundle2);

        IntelligentScreeningFragment fragment3 = new IntelligentScreeningFragment();
        Bundle bundle3 = new Bundle();
        bundle3.putInt("isMj", 3);
        fragment3.setArguments(bundle3);
        IntelligentScreeningFragment fragment4 = new IntelligentScreeningFragment();
        Bundle bundle4 = new Bundle();
        bundle4.putInt("isMj", 4);
        fragment4.setArguments(bundle4);

//        FlashFragment flashFragment = new FlashFragment();
//        PayCalendarFragment payCalendarFragment = new PayCalendarFragment();
        fragmentList.add(fragment);
//        fragmentList.add(rankingFragment);
        fragmentList.add(fragment1);
        fragmentList.add(fragment2);
        fragmentList.add(fragment3);
        fragmentList.add(fragment4);

        titles = new ArrayList<>();
        titles.add("智能筛选");
//        titles.add("排行");
//        titles.add("秒结");
//        titles.add("闪搜");
//        titles.add("打款日历");
//        titles.add("排行榜");
        titles.add("信托");
        titles.add("资管");
        titles.add("私募");
        titles.add("其他");
        new TabLayoutUtil(getActivity().getSupportFragmentManager(), rootView.findViewById(R.id.product_layout), fragmentList, titles, 0);



        appbar_layout.addOnOffsetChangedListener(new AppBarStateChangeListener(){

            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                LogUtils.d("STATE", state.name());
                if( state == State.EXPANDED ) {

                    //展开状态
//                    home_message_iv1.setVisibility(View.GONE);
//                    startAlphaAnimation(home_message_iv1, ALPHA_ANIMATIONS_DURATION, View.GONE);
//                    startAlphaAnimation(home_message_iv, ALPHA_ANIMATIONS_DURATION, View.VISIBLE);
//                    home_message_iv.setVisibility(View.VISIBLE);

                }else if(state == State.COLLAPSED){
//                    home_message_iv.setVisibility(View.GONE);
////                    //折叠状态
//                    home_message_iv1.setVisibility(View.VISIBLE);

//                    startAlphaAnimation(home_message_iv1, ALPHA_ANIMATIONS_DURATION, View.VISIBLE);
//                    startAlphaAnimation(home_message_iv, ALPHA_ANIMATIONS_DURATION, View.GONE);

                }else {
                    //中间状态
//                    home_message_iv.setVisibility(View.GONE);
////                    //折叠状态
//                    home_message_iv1.setVisibility(View.VISIBLE);
//                    startAlphaAnimation(home_message_iv1, ALPHA_ANIMATIONS_DURATION, View.VISIBLE);
//                    startAlphaAnimation(home_message_iv, ALPHA_ANIMATIONS_DURATION, View.GONE);

                }
            }
        });


        return rootView;
    }

    // 设置渐变的动画
    public static void startAlphaAnimation(View v, long duration, int visibility) {
        AlphaAnimation alphaAnimation = (visibility == View.VISIBLE)
                ? new AlphaAnimation(0f, 1f)
                : new AlphaAnimation(1f, 0f);

        alphaAnimation.setDuration(duration);
        alphaAnimation.setFillAfter(true);
        v.startAnimation(alphaAnimation);
        v.setVisibility(visibility);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @OnClick({R.id.menu_rl, R.id.home_search_tv, R.id.home_message_iv,R.id.home_message_iv1})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.home_search_tv://搜索
//                        soso_test

                MobclickAgent.onEvent(getActivity(), "soso_test");
                if (AppUtil.isExamined(getActivity())) {
                    startActivity(new Intent(getActivity(), SearchActivity.class));
//                    startActivity(new Intent(getActivity(), TermOfService.class));//SearchByConditionsActivity  AllMechanismActivity
                }
                break;
            case R.id.menu_rl:
                if (AppUtil.isExamined(getActivity())) {
                    broadside(AppUtil.getUserId(getActivity()));
//                    if (AppUtil.isFastDoubleClick()) {
//
//                    }
                }
                break;
            case R.id.home_message_iv://管家服务
                if (AppUtil.isExamined(getActivity())) {
                    startActivity(new Intent(getActivity(), ButlerServiceActivity.class));
                }
                break;
            case R.id.home_message_iv1:
                if (AppUtil.isExamined(getActivity())) {
                    startActivity(new Intent(getActivity(), ButlerServiceActivity.class));
                }
                break;
        }
    }

    private void broadside(String userId) {
         pd = CustomProgressDialog.createDialog(getActivity());
        HttpManager.getInstance().broadside(userId).subscribe(new BaseSubscriber(new HttpOnNextListener<BroadsideBean>() {
            @Override
            public void onNext(BroadsideBean o) {
                pd.dismiss();
                ((MainActivity) getActivity()).showPop(o);
            }
        }, this));
    }

    private void modifyFastQueryLabelIsNull(String userId){
        HttpManager.getInstance().modifyFastQueryLabelIsNull(userId).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                if(o.getResult().equals("1")){
                    SharedPreferencesUtils.put(getActivity(),SharedPreferencesUtils.HAVE_FLASH,true);
                }else{
                    SharedPreferencesUtils.put(getActivity(),SharedPreferencesUtils.HAVE_FLASH,false);
                }
            }
        }, this));
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void loadingFinished() {

    }

    @Override
    public void showMsg(String msg) {

    }

    @Override
    public <T> LifecycleTransformer<T> bindRecycler() {
        return null;
    }


    @Override
    public void onResume() {
        super.onResume();
        loadSearchKey();
        MobclickAgent.onPageStart("首页"); //统计页面("MainScreen"为页面名称，可自定义)
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("首页");
    }

    /**
     * 获取搜索关键词
     */
    private void loadSearchKey() {
        HttpManager.getInstance().defaultShow().subscribe(new BaseSubscriber(new HttpOnNextListener<SearchKeyBean>() {
            @Override
            public void onNext(SearchKeyBean o) {
                if (o.getContent() != null && !o.getContent().equals("")){
//                    homeSearchTv.setText("11111\"1111\"");

                    String str = "&quot;nihao";
//                    homeSearchTv.setText(Html.fromHtml(str));
                    homeSearchTv.setText(o.getContent());
                }
            }
        }, this));
    }


    public abstract static class AppBarStateChangeListener implements AppBarLayout.OnOffsetChangedListener {
        public enum State {
            EXPANDED,
            COLLAPSED,
            IDLE
        }
        private State mCurrentState = State.IDLE;
        @Override
        public final void onOffsetChanged(AppBarLayout appBarLayout, int i) {
            if (i == 0) {
                if (mCurrentState != State.EXPANDED) {
                    onStateChanged(appBarLayout, State.EXPANDED);
                }
                mCurrentState = State.EXPANDED;
            } else if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) {
                if (mCurrentState != State.COLLAPSED) {
                    onStateChanged(appBarLayout, State.COLLAPSED);
                }
                mCurrentState = State.COLLAPSED;
            } else {
                if (mCurrentState != State.IDLE) {
                    onStateChanged(appBarLayout, State.IDLE);
                }
                mCurrentState = State.IDLE;
            }
        }

        public abstract void onStateChanged(AppBarLayout appBarLayout, State state);


    }


}